// ValidationAspects
// Written by Mike Saunders
// Released under Microsoft Public License (Ms-PL)
using System;
using System.Linq.Expressions;
using System.Reflection;
using ValidationAspects.Sdk;

namespace ValidationAspects
{
	public static class TypeOf<T> where T : class
	{
		public static PropertyInfo GetProperty(Expression<Func<T, object>> expression)
		{
			Enforce.IsNotNull(expression, "expression");

			MemberExpression memberExpression = null;

			switch (expression.Body.NodeType)
			{
				case ExpressionType.Convert:
					memberExpression = ((UnaryExpression)expression.Body).Operand as MemberExpression;
					break;
				case ExpressionType.MemberAccess:
					memberExpression = expression.Body as MemberExpression;
					break;
			}

			if (memberExpression == null)
				throw new ArgumentException("Property could not be identified", "expression");

			PropertyInfo propertyInfo = typeof(T).GetProperty(memberExpression.Member.Name, BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.FlattenHierarchy);

			if (propertyInfo == null)
				throw new ArgumentException("Property could not be identified", "expression");

			return propertyInfo;
		}
	}
}